from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from pydantic import BaseModel
from app.database import get_db
import app.schemas as schemas
from app.services.torrent_service import TorrentService
import os

router = APIRouter()

class DeleteFilesRequest(BaseModel):
    file_ids: List[int]

@router.post("/delete")
async def delete_files(request: DeleteFilesRequest, db: Session = Depends(get_db)):
    """删除选中的文件"""
    service = TorrentService(db)
    deleted_files = []
    failed_files = []

    for file_id in request.file_ids:
        result = await service.get_scan_result(file_id)
        if result and os.path.exists(result.file_path):
            try:
                # 删除文件
                os.remove(result.file_path)
                # 更新状态
                await service.update_scan_result_status(file_id, "deleted")
                deleted_files.append(result.file_path)
            except Exception as e:
                failed_files.append({
                    "path": result.file_path,
                    "error": str(e)
                })

    return {
        "success": len(failed_files) == 0,
        "deleted_files": deleted_files,
        "failed_files": failed_files
    }

@router.get("/history", response_model=List[schemas.ScanResult])
async def get_delete_history(db: Session = Depends(get_db)):
    """获取文件删除历史"""
    service = TorrentService(db)
    return await service.get_scan_results(status="deleted")
